<template>
  <TresGroup>
    <template
      v-for="(line, index) in lines.children"
      :key="'fly_line_' + index"
    >
      <TresGroup>
        <!-- 静态白色线条 -->
        <TresLine
          :geometry="createLineGeometry(line.start, line.end, line.mid)"
          :material="{
            color: '#ffffff',
            linewidth: 2,
            transparent: true,
            opacity: 0.5,
          }"
        />

        <!-- 动态橙色线条 -->
        <TresLine
          ref="moveLinesRef[index]"
          :geometry="createLineGeometry(line.start, line.end, line.mid)"
          :material="createDashedMaterial('#ff7411')"
        />

        <!-- 终点球体 -->
        <TresMesh :position="line.end">
          <TresSphereGeometry :args="[0.06]" />
          <TresMeshBasicMaterial color="#ff7411" />
        </TresMesh>
      </TresGroup>
    </template>

    <!-- 起点球体 -->
    <TresMesh
      v-if="lines.children.length > 0"
      :position="lines.children[0].start"
    >
      <TresSphereGeometry :args="[0.1]" />
      <TresMeshBasicMaterial color="#ffffff" />
    </TresMesh>
  </TresGroup>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useFrame } from "@tresjs/core";
import {
  BufferGeometry,
  Float32BufferAttribute,
  LineDashedMaterial,
} from "three";

const props = defineProps({
  lines: {
    type: Object,
    required: true,
  },
});

// 存储动态线条的引用
const moveLinesRef = ref([]);

// 创建贝塞尔曲线路径
const createLineGeometry = (start, end, mid) => {
  const geometry = new BufferGeometry();

  // 计算贝塞尔曲线路径上的点
  const points = [];
  for (let t = 0; t <= 1; t += 0.05) {
    const x =
      Math.pow(1 - t, 2) * start[0] +
      2 * (1 - t) * t * mid[0] +
      Math.pow(t, 2) * end[0];
    const y =
      Math.pow(1 - t, 2) * start[1] +
      2 * (1 - t) * t * mid[1] +
      Math.pow(t, 2) * end[1];
    const z =
      Math.pow(1 - t, 2) * start[2] +
      2 * (1 - t) * t * mid[2] +
      Math.pow(t, 2) * end[2];
    points.push(x, y, z);
  }

  // 设置几何体顶点
  geometry.setAttribute("position", new Float32BufferAttribute(points, 3));
  geometry.computeLineDistances(); // 计算线段距离，用于虚线渲染

  return geometry;
};

// 创建虚线材质
const createDashedMaterial = (color) => {
  return new LineDashedMaterial({
    color,
    linewidth: 2,
    dashSize: 0.2,
    gapSize: 0.1,
    transparent: true,
    opacity: 1,
  });
};

// 动画循环 - 更新虚线偏移
useFrame((state) => {
  const delta = state.clock.getDelta();
  if (moveLinesRef.value.length > 0 && moveLinesRef.value[0]) {
    moveLinesRef.value.forEach((line) => {
      if (line && line.material && line.material.uniforms) {
        line.material.uniforms.dashOffset.value -= delta * 2;
      }
    });
  }
});
</script>
